<?php
namespace app\admin\controller;
use think\Controller;
use think\Session;
use think\request;
class Base extends Controller{
	public $permission;//存放权限
	public function _initialize(){
		$this->check_login();
		$this->check_permission();
		$this->header();
		$this->location();
	}
	/**
	 * 检查登录
	 */
	private  function check_login(){
		if (session("is_login") != 1){
			$this->redirect('Login/login');;exit;
		}
	}
	/**
	 * 设置面包屑方法
	 */
	private function location(){
		$loaction_p='';
		$request=  \think\Request::instance();
		$where['action'] = $request->controller();
		$loaction = db('AdminMenu')->where($where)->find();
		if($loaction){
			$where1['id'] = $loaction['p_id'];
			$loaction_p = db('AdminMenu')->where($where1)->find();
		}
	
		$this->assign("loaction",$loaction);
		$this->assign("loaction_p",$loaction_p);
	}
	/*
	 * 设置导航方法
	*
	*/
	private function header(){
		//排序方法,数值越小越靠前
		function menu_sort($a, $b) {
			$al = $a['sort'];
			$bl = $b['sort'];
			if ($al == $bl)
				return 0;
			return ($al > $bl) ? 1 : -1;
		}
		if ($this->permission == 'all'){
			$menus = db('AdminMenu')->select();
		}else{
			$menus = db('AdminMenu')->where("id in ($this->permission) or p_id=0")->select();
		}
		$menu_arr = array();
		foreach ($menus as $m) {
			if ($m['p_id']==0){
				$menu_arr[] = $m;
			}
		}
		foreach ($menu_arr as $k=>$m_arr){
			foreach ($menus as $m) {
				if ($m['p_id']==$m_arr['id']){
					$menu_arr[$k]['sub_menu'][] = $m;
				}
			}
		}
// 		print_r($menu_arr);
// 		exit();
		$this->assign('menu_arr',$menu_arr);
	}
	/**
	 * 权限检查
	 */
	private function check_permission(){
		$request=  \think\Request::instance();
		$id = session('admin_id');
		$obj = db('admin')->where("id=$id")->find();
		$where['id'] = $obj['roleid'];
		$per = db('AdminRole')->where($where)->find();
		$this->permission = $per['menu_ids'];
		if($per['menu_ids'] != 'all'){
			$action = $request->controller().'-'.$request->action();//获取菜单方法
			$am = db('AdminMenu')->where("action='".$request->controller()."' and function='".$request->action()."'")->find();
			if ($am && !in_array($am['id'],explode(',',$per['menu_ids']))){//判断是否拥有菜单权限
				echo '没有权限';exit;
			}
		}
	}
	/**
	 * 上传方法
	 */
	public function upload_(Request $request,$path){
		$file = $request->file('file');
		if (empty($file)) {
			$this->error('请选择上传文件');
		}
		// 移动到框架应用根目录/public/uploads/ 目录下
		$info = $file->validate(['size'=>2048000,'ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads'.$path);
		if ($info) {
			$img_url= $info->getRealPath();
		} else {
			// 上传失败获取错误信息
			return false;
		}
		return $info;
	}
} 